var imgInterval;
var sparkle;
$(document).on('pageinit', "#_start_html", function(e,eventData){
    $("title").html("年会签到");
    signInShow(eventData);
    imgInterval = setInterval(function(){
        var pos = rd(0,$('#content').find("img").not(".join").length);
        $($('#content').find("img").not(".join")[pos]).animate({'opacity':'.6'},50).animate({'opacity':'0.4'},50);
    },20);
    //sparkle = new Sparkle($('#sparkle'), {
    //    width: 500,
    //    height: 500,
    //    color: "rainbow",
    //    count: 300,
    //    overlap: 0
    //});
});
var cjObj = {
  cjFlag:false,
  title:"抽取奖项",
  cjNum:3
};
var userListJson = [];
var cjStart = function(){
    $('.tempImg').remove();
    imgInterval = setInterval(function(){
        var pos = rd(0,$('#content').find("img").length);
        $($('#content').find("img")[pos])
            .animate({'opacity':'.6'},50)
            .animate({'opacity':'.4'},50);
    },20);
    //sparkle.out();
};
var cjEnd = function(zjNum){
    clearInterval(imgInterval);
    //sparkle.out();
    var _rdNum = rd(0,userListJson.length-1);
    var winUser = userListJson[_rdNum];
    console.log(winUser);
    $.get(serverAddress+"users/zj",{
        id:winUser.id,
        zj:zjNum
    });
    var $img = $("img[alt='"+winUser.name+"']");
    $img.addClass("join");
    var _x = $img.position().left;
    var _y = $img.position().top;

    var $tempImg = $("<img class='tempImg' src='"+$img.attr("src")+"'/>");
    $tempImg.css({
        top : _y,
        left: _x,
        width:$img.width(),
        height:$img.height(),
        position:"absolute",
        "z-index":100
    });
    var $thumbsWrapper = $('#thumbsWrapper');
    $thumbsWrapper.prepend($tempImg);
    $tempImg.animate({
        top:($thumbsWrapper.height()-$img.height()*2)/2,
        left:($thumbsWrapper.width()-$img.width())/2-$img.width()
    },1000,function(){
        //sparkle.over();
    }).animate({
        width:$img.width()*5,
        height:$img.height()*5,
        top:($thumbsWrapper.height()-$img.height()*5)/2,
        left:($thumbsWrapper.width()-$img.width()*5)/2,
        opacity:1
    },2000,function(){
        $('#img_div_'+winUser.id).remove();
        delete userListJson[_rdNum];
    })
};
var cjInit = function(){
    $('#3dBackGround').show();
    $('#3dParticle').show();
    if(!cjObj.cjFlag){
        return
    }
    //sparkle.out();
    $('.tempImg').remove();
    $('#content').find("img").css({
        'opacity':'.4'
    });
    clearInterval(imgInterval);
    $("title").html(cjObj.title);
    // 移除未到场及不参与抽奖人士
    $.get(serverAddress+"users/ncj",function(json){
        var _i;
        for(_i in json){
            try{
                $('#img_div_'+json[_i]["id"]).remove();
            }catch(_expt){
                console.error(_expt);
            }
        }
    });
    // 初始化参与抽奖人员
    $.get(serverAddress+"users/cj",function(json){
        userListJson = json;
    });
    // 把所有人员黑屏掉
    $('.join').removeClass('join');
};
$(document).on('pageshow', "#_start_html", cjInit);
$(document).on('pageshow', "#_year_start_html", function(e,eventData){
    $("title").html("年会开始");
    $('#3dBackGround').hide();
    $('#3dParticle').hide();
    S.init();
});
$(document).on('pageshow', "#_chezongzhici_html", function(e,eventData){
    $("title").html("车总致辞");
    var audio = document.getElementById('audioPlayer');
    audio.pause();
    audio.src = "/audio/喜洋洋.mp3";
    audio.load();
    audio.play();
});

$(document).on('pageshow', "#_youxiubumen_html", function(e,eventData){
    $("title").html("优秀部门");
    //$(document).snowfall('clear');
    var audio = document.getElementById('audioPlayer');
    audio.pause();
    audio.src = "/audio/signin1.mp3";
    setTimeout(function(){
        audio.play();
    },30);
});

var yxygScene;
var photostemp = [];
$(document).on('pageinit', "#_start1_html", function(e,eventData){
    var container, scene, camera, renderer, controls, stats;
    var keyboard = new THREEx.KeyboardState();
    var clock = new THREE.Clock();
// custom global variables
    var cube;
    var photo;

    var delta = clock.getDelta(); // seconds.
    var moveDistance = 200 * delta; // 200 pixels per second
    var randomRect=[];
    var rotateAngle = Math.PI / 2 * delta;

    init();
    animate();



// FUNCTIONS
    function init()
    {
        // SCENE
        scene = new THREE.Scene();
        yxygScene = scene;
        // CAMERA
        var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
        var VIEW_ANGLE = 75, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 2, FAR = 20000;
        camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
        scene.add(camera);
        camera.position.set(0,100,400);
        camera.rotation.set(0,0,400);
        camera.lookAt(scene.position);
        // RENDERER
        if ( Detector.webgl )
            renderer = new THREE.WebGLRenderer( { antialias : true, devicePixelRatio : 1 } );
        else
            renderer = new THREE.CanvasRenderer();
        renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        container = document.getElementById( 'startCavus' );
        container.appendChild( renderer.domElement );
        // EVENTS
        THREEx.WindowResize(renderer, camera);
        THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
        // CONTROLS
        controls = new THREE.OrbitControls( camera, renderer.domElement );
        controls.autoRotate = true;
        controls.autoRotateSpeed = 0.5;
        // STATS
//        stats = new Stats();
//        stats.domElement.style.position = 'absolute';
//        stats.domElement.style.bottom = '0px';
//        stats.domElement.style.zIndex = 100;
//        container.appendChild( stats.domElement );
        // LIGHT
        var light = new THREE.PointLight(0xff0000);
        light.position.set(0,450,0);
        scene.add(light);


//        var imagePrefix = "images/DarkSea-";
//        var directions  = ["xpos", "xneg", "ypos", "yneg", "zpos", "zneg"];
//        var imageSuffix = ".jpg";
        var imagePrefix = "";
        var directions  =  ["images/park/px.jpg", "images/park/nx.jpg", "images/park/py.jpg", "images/park/ny.jpg", "images/park/pz.jpg", "images/park/nz.jpg"]
        var imageSuffix = ".png";
        var skyGeometry = new THREE.CubeGeometry( 5000, 5000, 5000 );

        var materialArray = [];
        for (var i = 0; i < 6; i++)
            materialArray.push( new THREE.MeshBasicMaterial({
                map: THREE.ImageUtils.loadTexture( directions[i]),
                side: THREE.BackSide
            }));
        var skyMaterial = new THREE.MeshFaceMaterial( materialArray );
        var skyBox = new THREE.Mesh( skyGeometry, skyMaterial );
        scene.add( skyBox );
        // FLOOR
        
        // SKYBOX/FOG
        var skyBoxGeometry = new THREE.CubeGeometry( 5000, 5000, 5000 );
        var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, side: THREE.BackSide } );
        var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
        scene.add(skyBox);

        ////////////
        // CUSTOM //
        ////////////
        emitterSettings = {
            type: 'sphere',
            positionSpread: new THREE.Vector3(10, 100, 10),
            acceleration: new THREE.Vector3(0, -20, 0),
            radius: 10,
            speed: 60,
            speedSpread: 40,
            sizeStart: 40,
            // sizeStartSpread: 30,
            sizeEnd: 10,
            opacityStart: 1,
            opacityMiddle: 1,
            opacityEnd: 0,
            colorStart: new THREE.Color('white'),
            colorStartSpread: new THREE.Vector3(0.5,0.5,0.5),
            colorMiddle: new THREE.Color('red'),
            colorEnd: new THREE.Color('red'),
            particlesPerSecond: 2000,
            alive: 0, // initially disabled, will be triggered later
            emitterDuration: 0.1
        };

        // Create a particle group to add the emitter
        this.particleGroup = new ShaderParticleGroup(
            {
                texture: THREE.ImageUtils.loadTexture('images/spark.png'),
                maxAge: 2,
                colorize: 1,
                blending: THREE.AdditiveBlending
            });

        var colors = ["red", "orange", "yellow", "green", "blue", "violet", "pink", "magenta", "cyan", "steelblue", "seagreen"];
        for (var i = 0; i < colors.length; i++)
        {
            emitterSettings.colorMiddle = new THREE.Color( colors[i] );
            emitterSettings.colorEnd = new THREE.Color( colors[i] );
            particleGroup.addPool( 1, emitterSettings, false );
        }

        // Add the particle group to the scene so it can be drawn.
        scene.add( particleGroup.mesh );

        this.engine = new ParticleEngine();
        engine.setValues( Examples.snow );
        engine.initialize(scene);
    }

    function animate()
    {
        requestAnimationFrame( animate );
        render();
        update();
        TWEEN.update();
    }

    function restartEngine(parameters)
    {
        resetCamera();

        engine.destroy(scene);
        engine = new ParticleEngine();
        engine.setValues( parameters );
        engine.initialize();
    }

    function resetCamera()
    {
        // CAMERA
        var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
        var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
        camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
        //camera.up = new THREE.Vector3( 0, 0, 1 );
        camera.position.set(100,400,400);
        camera.lookAt(scene.position);
        scene.add(camera);

        controls = new THREE.OrbitControls( camera, renderer.domElement );
        THREEx.WindowResize(renderer, camera);
    }


    function update()
    {
        controls.update();
        var dt = clock.getDelta();
        engine.update( dt * 0.5 );
        particleGroup.tick( dt );
        if ( Math.random() < dt ){
            particleGroup.triggerPoolEmitter( 1, randomVector3(-200,200, 50,200, -200,-100) );
        }
        for(_i in photostemp){
            photostemp[_i].lookAt(camera.position);
        }

    }
    function randomVector3(xMin, xMax, yMin, yMax, zMin, zMax)
    {
        return new THREE.Vector3( xMin + (xMax - xMin) * Math.random(),
                yMin + (yMax - yMin) * Math.random(), zMin + (zMax - zMin) * Math.random() );
    }
    function render()
    {
        renderer.render( scene, camera );
    }

});

$(function(){
    $(document).transition('options', {domCache : true});
    var audio = document.getElementById('audioPlayer');
    var socket = io.connect(serverPath);
    socket.emit(serverLoginEvent,{id:"show"});
    //监听发送登录的命令
    socket.on(clientLoginBackEvent, function(msg){
        $('#message').html(msg.message);
    });

    //监听操作回传命令
    socket.on(clientShowEvent, function(msg){
        console.log(msg.cmd);
        cjObj.cjFlag=false;
        switch(msg.cmd)
        {
            case "s1":
                $(document).transition("to","/start.html");
                break;
            case "m1":
                audio.pause();
                audio.src = "/audio/越难越爱.mp3";
                audio.load();
                audio.play();
                break;
            case "m2":
                audio.pause();
                break;
            case "p1":
                console.log(msg.name);
                var $img = $("img[alt='"+msg.name+"']");
                $img.addClass("join");
                var _x = $img.position().left;
                var _y = $img.position().top;

                var $tempImg = $("<img src='"+$img.attr("src")+"'/>");
                $tempImg.css({
                    top : _y,
                    left: _x,
                    width:$img.width(),
                    height:$img.height(),
                    position:"absolute",
                    "z-index":100
                });

                $img.after($tempImg);
                var pos = rd(1,3);
                audio.pause();
                audio.src = "/audio/signin"+pos+".mp3";
                audio.load();
                audio.play();
                var $thumbsWrapper = $('#thumbsWrapper');
                $tempImg.animate({
                    top:($thumbsWrapper.height()-$img.height()*2)/2,
                    left:($thumbsWrapper.width()-$img.width())/2-$img.width()
                },1500).animate({
                    width:$img.width()*5,
                    height:$img.height()*5,
                    top:($thumbsWrapper.height()-$img.height()*5)/2,
                    left:($thumbsWrapper.width()-$img.width()*5)/2,
                    opacity:1
                },2000).animate({
                    width:$img.width(),
                    height:$img.height(),
                    top:_y,
                    left:_x
                },2000,function(){
                    $tempImg.remove();
                    $img.css({
                        opacity:1
                    });
                    $img.parent().find("span").css("color","white");
                    if(!audio.parsed){
                        audio.pause();
                    }
                });
                break;
            case "s2":
                //$(document).snowfall('clear');
                audio.src = "/audio/signin1.mp3";
                audio.load();
                audio.play();
                $(document).transition("to","/year_start.html");
                break;
            case "s3":
                $(document).transition("to","/youxiubumen.html","slidedown");
                break;
            case "y1":
                audio.pause();
                $("#yxbm_content").append('<span style="font-size:100px; display: block;  text-align: center; height:120px; line-height: 120px; color:#ffff00; font-weight: bold">'+msg.dept+'</span>');
                break;
            case "s4":
                audio.pause();
                audio.src = "/audio/保龄男孩.mp3";

                audio.load();
                audio.play();
                $(document).transition("to","/start1.html","fade");
                break;
            case "g1":
                var tempArray = [
                    '王召','赵灿','戴晨','司晓岩','王国威','刘艳伟','李美琳',
                    '马良','杨飞飞','孙松','梁召','李墨','贺林','郭立仁',
                    '尚晨光','王峰','程涛','李攀','田会生','许建强','郑婧'];

                var initPos = [];

                for ( var i = 0, l = tempArray.length; i < l; i ++ ){
                    var runnerTexture = new THREE.ImageUtils.loadTexture( 'photo/'+tempArray[i]+".jpg" );
                    var runnerMaterial  = new THREE.MeshBasicMaterial( { map: runnerTexture, side:THREE.DoubleSide } );
                    var runnerGeometry = new THREE.PlaneGeometry(100, 100, 1, 1);
                    var photo = new THREE.Mesh(runnerGeometry, runnerMaterial);
                    var phi = Math.acos( -1 + ( 2 * i ) / l );
                    var theta = Math.sqrt( l * Math.PI ) * phi;

                    initPos.push({
                        x: 200 * Math.cos( theta ) * Math.sin( phi ),
                        y: 200 * Math.sin( theta ) * Math.sin( phi ),
                        z:200 * Math.cos( phi )
                    });
                    var sss = i%2;
                    var ssss = -1;
                    if(sss==0){
                        ssss = 1;
                    }
                    photo.userName = tempArray[i];
                    photo.position.x = Math.random()*900*ssss +(900*ssss);
                    photo.position.y = Math.random()*900*ssss+(900*ssss);
                    photo.position.z = Math.random()* 900*ssss+(900*ssss);
                    photostemp.push(photo);

                }
                var photos = msg.content.split(",");
                for ( var i = 0, l = photos.length; i < l; i ++ ){
                    var phPos = tempArray.indexOf(photos[i]);
                    if(phPos!=-1){
                        var _p = photostemp[phPos];
                        var _initP = initPos[phPos];
                        yxygScene.add(_p);
                        new TWEEN.Tween(_p.rotation )
                            .to( { x: 0, y: 15, z: 0 }, Math.random() * 2000 +8000 )
                            .easing( TWEEN.Easing.Exponential.InOut )
                            .start();
                        new TWEEN.Tween(_p.position )
                            .to( { x: _initP.x, y: _initP.y, z: _initP.z }, Math.random() * 2000 +4000 )
                            .easing( TWEEN.Easing.Exponential.InOut )
                            .start();

                        var materialFront = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
                        var materialSide = new THREE.MeshBasicMaterial( { color: 0x000088 } );
                        var materialArray = [ materialFront, materialSide ];

                        var textGeom = new THREE.TextGeometry( _p.userName+"车总致辞",
                            {
                                font:"microsoft yahei ui",
                                size : 30,
                                height : 4,
                                curveSegments : 5,
                                bevelEnabled : true,
                                bevelThickness : 0.2,
                                bevelSize : 0.1,
                                weight : "normal",
                                style : "normal"
                            });
                        // font: helvetiker, gentilis, droid sans, droid serif, optimer
                        // weight: normal, bold

                        var textMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
                        textMaterial.ambient = new THREE.Color(0xFF0000);
                        var textMesh = new THREE.Mesh(textGeom, textMaterial );

                        textGeom.computeBoundingBox();
                        var textWidth = textGeom.boundingBox.max.x - textGeom.boundingBox.min.x;

                        //textMesh.pos  ition.set( -0.5 * textWidth, 50, 100 );
                        //textMesh.rotation.z = -Math.PI / 4;
                        textMesh.position.x = _initP.x;
                        textMesh.position.y = _initP.y-80;
                        textMesh.position.z =_initP.z;
                        textMesh.rotation.x = _p.rotation.x;
                        textMesh.rotation.y = _p.rotation.y;
                        textMesh.rotation.z = _p.rotation.z;
                        yxygScene.add(textMesh);
                    }
                }
                break;
            case "c1in":
                cjObj = {
                    cjFlag:true,
                    title:"抽取一等奖",
                    cjNum:1
                };
                $(document).transition("to","/start.html");
                cjInit();
                break;
            case "c1s":
                cjStart();
                break;
            case "c1e":
                cjEnd(1);
                break;
            case "c2in":
                cjObj = {
                    cjFlag:true,
                    title:"抽取二等奖",
                    cjNum:2
                };
                $(document).transition("to","/start.html");
                cjInit();
                break;
            case "c2s":
                cjStart();
                break;
            case "c2e":
                cjEnd(2);
                break;
            case "c3in":
                cjObj = {
                    cjFlag:true,
                    title:"抽取三等奖",
                    cjNum:3
                };
                $(document).transition("to","/start.html");
                cjInit();
                break;
            case "c3s":
                cjStart();
                break;
            case "c3e":
                cjEnd(3);
                break;
            case "min":
                $(document).transition("to","/mv.html","fade");
                break;
            case "ms":
                video.src = "video/"+msg.content;
                video.load();
                video.play();
                break;
            case "me":
                video.pause();
                video.src = "";
                break;
            case "vol+":
                audio.volume += 0.05;
                break;
            case "vol-":
                audio.volume -= 0.05;
                break;
            default:
                break;
        }
    });
});